/*jslint vars: true, forin: true, plusplus: true */
/*global angular: false, engine: false*/
engine.factory("Result", function (Entity) {
	'use strict';
	/**
	 * 结果对象，在process建立时一起构造
	 * 在process运行时打快照，在step发生异常时增加log
	 * 在process运行结束时输出result的Json快照
	 *
	 * @class DelayStep
	 * @extends Step
	 * @constructor
	 */
	var Result = function Result(process) {
		this.$process = process;

		this.snapshot = {
			steps: [],
			process: {}
		};
		this.logs = {
			errors: [],
			times: {}
		};

		Entity.call(this);
	};
	Result.prototype = new Entity();
	Result.prototype.constructor = Result;

	/**
	 * 增加一条日志
	 * log的要素包括loop、counter和action(param)
	 *
	 * @method addLog
	 * @returns {Result} this
	 * @chainable
	 * @example
	 *		[Result].addLog([
	 *			...
	 *			{
	 *				loop: 45,
	 *				counter: 4,
	 *				action: {
	 *					val: "dfjs@dfe.cn"
	 *				}
	 *			},...
	 *		]);
	 */
	Result.prototype.addLog = function (log) {
		this.logs.errors.push(log);

		return this;
	};

	Result.prototype.addTime = function (time_length, flag) {
		var times = this.logs.times;
		if (angular.isUndefined(times[flag])) {
			times[flag] = [time_length];
		} else {
			times[flag].push(time_length);
		}

		return this;
	};

	/**
	 * 截取process快照
	 *
	 * @method setSnapshot
	 * @param {Process} process
	 * @returns {Result} this
	 * @chainable
	 */
	Result.prototype.setSnapshot = function () {
		var process = this.$process;
		var i, len = process.getLength();

		this.snapshot.process = process.toOptions();
		for (i = 0; i < len; i++) {
			this.snapshot.steps.push(process.program[i].toOptions());
		}

		return this;
	};

	/**
	 * 生成Json字符串快照
	 * 用于组装报文发送
	 *
	 * @method setSnapshot
	 * @returns {string} JsonString
	 * @chainable
	 */
	Result.prototype.toJson = function () {
		return angular.toJson({
			snapshot: this.snapshot,
			logs: this.logs
		});
	};

	return Result;
});
